#include "mysqlFunc.h"

int mysqlInit(MYSQL **pmysqlConn){
    char * host = "192.168.0.69";
    char * user = "root";
    char * passwd = "1234";
    char * db = "54test";

    *pmysqlConn = mysql_init(NULL);
    if(mysql_real_connect(*pmysqlConn, host, user, passwd, db, 0, NULL, 0) == NULL){
        printf("error:%s\n", mysql_error(*pmysqlConn));
        return EXIT_FAILURE;
    }
    printf("server was connected mysql!\n");
    return 0;
}

int mysqlQuery(MYSQL *pmysqlConn, const char *userName, int *pQueryResult){
    //1、执行查询
    char query[300] = "select * from user where username = '";
    sprintf(query, "%s%s%s", query, userName, "';");
    printf("query = %s\n", query);
    
    int ret = mysql_query(pmysqlConn, query);
    if(0 != ret){
        printf("error query1: %s\n", mysql_error(pmysqlConn));
        return EXIT_FAILURE;
    }
    
    //2、获取结果集，N行数据
    MYSQL_RES * result = mysql_store_result(pmysqlConn);
    if(result == NULL){
        printf("eooer query2: %s\n", mysql_error(pmysqlConn));
        return EXIT_FAILURE;
    }
    int rows = mysql_num_rows(result);
    int cols = mysql_num_fields(result);
    printf("rows = %d, cols = %d\n", rows, cols);
    if(0 == rows){
        //没查到
        printf("未查询到用户: %s\n", userName);
        *pQueryResult = -1;
    }
    else{
        printf("查询到用户: %s\n", userName);
        *pQueryResult = 1;
    }

    //3、获取每一行的数据
    MYSQL_ROW row;
    if(rows > 0){
        while((row = mysql_fetch_row(result)) != NULL){
            for(unsigned int i = 0; i < cols; ++i){
                printf("%s\t", row[i]);
            }
            printf("\n");
        }
    }

    //4、释放结果集
    mysql_free_result(result);
    
    return 0;
}

int fileTableInit(const char* fileName, int pre_id, const char* path, 
                    const char* type, const char* fileMd5, int tomb, void *arg){
    fileTable_t *pfileTable = (fileTable_t *)arg;
    bzero(pfileTable, sizeof(fileTable_t));
    memcpy(pfileTable->fileName, fileName, strlen(fileName));
    memcpy(pfileTable->fileName, fileName, strlen(fileName));
    memcpy(pfileTable->fileName, fileName, strlen(fileName));
    memcpy(pfileTable->fileName, fileName, strlen(fileName));
    memcpy(pfileTable->fileName, fileName, strlen(fileName));
    memcpy(pfileTable->fileName, fileName, strlen(fileName));
}

int mysqlInsert(MYSQL *pmysqlConn, const char* tableName, void *arg, int *insertResult){
    if(strcmp(tableName, "user") == 0){
        userTable_t *puserTable = (userTable_t *)arg;
        char query[1024] = "insert into user(username, salt, cryptpasswd, pwd) values(";
        sprintf(query, "%s%s%s%s%s", query, "'", puserTable->userName, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", puserTable->userSalt, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", puserTable->userCryptpasswd, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", puserTable->userPwd, "'", ");");
        printf("query = %s\n", query);
        int ret = mysql_query(pmysqlConn, query);
        if(0 != ret){
            printf("插入用户表失败\n");
            printf("error query: %s\n", mysql_error(pmysqlConn));
            *insertResult = -1;
            return EXIT_FAILURE;
        }
    }
    else if(strcmp(tableName, "file") == 0){
        fileTable_t *pfileTable = (fileTable_t *)arg;
        char query[1024] = "insert into file(filename, username, pre_id, path, type, md5, tomb) values(";
        sprintf(query, "%s%s%s%s%s", query, "'", pfileTable->fileName, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", pfileTable->userName, "'", ", ");
        sprintf(query, "%s%s%d%s%s", query, "'", pfileTable->pre_id, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", pfileTable->path, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", pfileTable->type, "'", ", ");
        sprintf(query, "%s%s%s%s%s", query, "'", pfileTable->fileMd5, "'", ", ");
        sprintf(query, "%s%s%d%s%s", query, "'", pfileTable->tomb, "'", ");");
        printf("query = %s\n", query);
        int ret = mysql_query(pmysqlConn, query);
        if(0 != ret){
            printf("插入文件表失败\n");
            printf("error query: %s\n", mysql_error(pmysqlConn));
            *insertResult = -1;
            return EXIT_FAILURE;
        }
    }
    else{
        printf("tableName error!\n");
        return -1;
    }
    *insertResult = 1;
    return 0;
}

int generateInt(int length, char str[]){
    int flag, i;
    char* string;
    srand((unsigned) time(NULL));
    if((string = (char*) malloc(length)) == NULL){
        printf("malloc failed!flag:14\n");
        return 0;
    }
    for(i = 0; i < length; i++){
        flag = rand() % 3;
        switch (flag) {
            case 0: string[i] = '0' + rand() % 10; break;
            default: string[i] = '1'; break;
        }
    }
    string[length] = '\0';
    memcpy(str, string, length);
    return 0;
}

int generateStr(int length, char str[]){
    int flag, i;
    char* string;
    srand((unsigned) time(NULL ));
    if ((string = (char*) malloc(length)) == NULL ) {
        printf("malloc failed!flag:14\n");
        return 0;
    }
    for (i = 0; i < length+1; i++) {
    flag = rand() % 3;
    switch (flag) {
        case 0: string[i] = 'A' + rand() % 26; break;
        case 1: string[i] = 'a' + rand() % 26; break;
        case 2: string[i] = '0' + rand() % 10; break;
        default: string[i] = 'x'; break;
    }
    }
    string[length] = '\0';
    memcpy(str, string, length);
    return 0;
}

int generateSalt(char salt[]){
    char str1[2];
    generateInt(1, str1);
    //printf("str1 = %s\n", str1);
    char str2[2];
    generateInt(1, str2);
    //printf("str2 = %s\n", str2);
    char str3[10];
    generateStr(7, str3);
    //printf("str3 = %s\n", str3);
    bzero(salt, strlen(salt));
    sprintf(salt, "%s%s%s%s%s%s", "$", str1, "$", str2, str3, "$");
    //printf("salt = %s\n", salt);
    return 0;
}

int passwdVerify(MYSQL *pmysqlConn, const char* userName, const char* userPasswd, int *pQueryResult){
    char query[300] = "select * from user where username = '";
    sprintf(query, "%s%s%s", query, userName, "';");
    printf("query = %s\n", query);
    
    int ret = mysql_query(pmysqlConn, query);
    if(0 != ret){
        printf("error query1: %s\n", mysql_error(pmysqlConn));
        return EXIT_FAILURE;
    }
    
    //2、获取结果集，N行数据
    MYSQL_RES * result = mysql_store_result(pmysqlConn);
    if(result == NULL){
        printf("eooer query2: %s\n", mysql_error(pmysqlConn));
        return EXIT_FAILURE;
    }
    int rows = mysql_num_rows(result);
    int cols = mysql_num_fields(result);
    printf("rows = %d, cols = %d\n", rows, cols);
    if(0 == rows){
        //没查到
        printf("未查询到用户: %s\n", userName);
        *pQueryResult = -1;
        return 0;
    }

    //3、获取每一行的数据
    MYSQL_ROW row;
    char salt[20] = {0};
    char mysqlCryptpasswd[300] = {0};
    if(rows > 0){
        while((row = mysql_fetch_row(result)) != NULL){
            for(unsigned int i = 0; i < cols; ++i){
                printf("%s\t", row[i]);
                // id-0, username-1, salt-2, cyrptpasswd-3, pwd-4
                if(2 == i){
                    memcpy(salt, row[i], strlen(row[i]));
                }
                if(3 == i){
                    memcpy(mysqlCryptpasswd, row[i], strlen(row[i]));
                }
            }
            printf("\n");
        }
    }
    //验证用户密码
    char *cryptPasswd = crypt(userPasswd, salt);
    if((strcmp(mysqlCryptpasswd, cryptPasswd)) == 0){
        //密码正确
        *pQueryResult = 1;
    }
    else{
        *pQueryResult = -1;
    }

    //4、释放结果集
    mysql_free_result(result);
    return 0;
}

int fileTableQuery(MYSQL *pmysqlConn, const char* tableName,
                    const char* username, const char* path, fileTable_t* fileTable){
    char query[300] = "select * from ";
    //"select * from file where user = '"
    sprintf(query, "%s%s%s", query, tableName, " where username = '");

    //"select * from file where user = 'userName' and path = '"
    sprintf(query, "%s%s%s", query, username, "' and path = '");

    //"select * from file where user = 'userName' and path = 'path';"
    sprintf(query, "%s%s%s", query, path, "';");
    printf("query = %s\n", query);
    
    int ret = mysql_query(pmysqlConn, query);
    if(0 != ret){
        printf("error query1: %s\n", mysql_error(pmysqlConn));
        fileTable->queryResult = -1;
        return EXIT_FAILURE;
    }
    
    //2、获取结果集，N行数据
    MYSQL_RES * result = mysql_store_result(pmysqlConn);
    if(result == NULL){
        printf("eooer query2: %s\n", mysql_error(pmysqlConn));
        fileTable->queryResult = -1;
        return EXIT_FAILURE;
    }
    int rows = mysql_num_rows(result);
    int cols = mysql_num_fields(result);
    printf("rows = %d, cols = %d\n", rows, cols);
    if(0 == rows){
        //没查到
        printf("未查询到用户: %s\n", fileTable->userName);
        fileTable->queryResult = -1;
        return 0;
    }

    //3、获取每一行的数据
    MYSQL_ROW row;
    if(rows > 0){
        fileTable->queryResult = 1;
        while((row = mysql_fetch_row(result)) != NULL){
            for(unsigned int i = 0; i < cols; ++i){
                printf("%s\t", row[i]);
                //id-0, filename-1, user-2, pre_id-3, path-4, type-5, md5-6, tomb-7
                if(0 == i){
                    fileTable->id = atoi(row[i]);
                }
                if(1 == i){
                    memcpy(fileTable->fileName, row[i], strlen(row[i]));
                }
                if(2 == i){
                    memcpy(fileTable->userName, row[i], strlen(row[i]));
                }
                if(3 == i){
                    fileTable->pre_id = atoi(row[i]);
                }
                if(4 == i){
                    memcpy(fileTable->path, row[i], strlen(row[i]));
                }
                if(5 == i){
                    memcpy(fileTable->type, row[i], strlen(row[i]));
                }
                if(6 == i){
                    if((strcmp(fileTable->type, "d")) == 0){
                        //目录文件
                        fileTable->fileMd5 = NULL;
                    }
                    else{
                        memcpy(fileTable->fileMd5, row[i], strlen(row[i]));
                    }
                }
                if(7 == i){
                    fileTable->tomb = atoi(row[i]);
                }
            }
            printf("\n");
        }
    }

    //4、释放结果集
    mysql_free_result(result);
    return 0;
}